package com.jn.web.controller.common;


import com.jn.common.core.domain.AjaxResult;
import com.jn.common.core.domain.R;
import com.jn.system.domain.dto.FileIdRequest;
import com.jn.system.domain.dto.FileOperateRequest;
import com.jn.system.domain.dto.MergeChunksRequest;
import com.jn.system.service.IChunkFileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

/**
 * 分片上传
 *
 * @author wushaorui
 */
@RestController
@RequestMapping("/chunk/file")
public class ChunkFileController {

    @Autowired
    private IChunkFileService chunkFileService;

    /**
     * 获取文件唯一标识（接收JSON参数）
     */
    @PostMapping("/upload/get-file-id")
    public R<String> getFileId(@Validated @RequestBody FileIdRequest request) {
        String fileId = chunkFileService.getFileId(
                request.getFileName(),
                request.getFileSize(),
                request.getFileType()
        );
        return R.ok(fileId);
    }

    /**
     * 上传文件分片（接收FormData参数，包含文件流）
     */
    @PostMapping("/upload/chunk")
    public AjaxResult uploadChunk(
            @RequestParam("fileId") String fileId,
            @RequestParam("chunk") Integer chunk,
            @RequestParam("file") MultipartFile file) {
        // 参数校验
        if (file == null || file.isEmpty()) {
            return AjaxResult.error("分片文件不能为空");
        }
        return chunkFileService.uploadChunk(fileId, chunk, file);
    }

    /**
     * 合并文件分片（接收JSON参数）
     */
    @PostMapping("/upload/merge")
    public AjaxResult mergeChunks(@Validated @RequestBody MergeChunksRequest request) {
        return chunkFileService.mergeChunks(
                request.getFileId(),
                request.getFileName(),
                request.getChunks()
        );
    }

    /**
     * 取消文件上传（接收JSON参数）
     */
    @PostMapping("/upload/cancel")
    public AjaxResult cancelUpload(@Validated @RequestBody FileOperateRequest request) {
        return chunkFileService.cancelUpload(request.getFileId());
    }
}
